//
//  HamburgerButton.swift
//  Hamburger Button
//
//  Created by Robert Böhnke on 02/07/14.
//  Copyright (c) 2014 Robert Böhnke. All rights reserved.
//

import CoreGraphics
import QuartzCore
import UIKit

enum HamburgerButtonState{

    case satrt
    case stop(state:Int)
}

class HamburgerButton : UIButton {
    
    var circlePointView:UIView!
    
    let outline: CGPath = {
        let path = CGPathCreateMutable()
        CGPathAddArc(path, nil, 0, 0, 40, 0, CGFloat(M_PI * 2), true)
        return path
    }()

    let menuStrokeStart: CGFloat = 0.0
    let menuStrokeEnd: CGFloat = 1.0

    let hamburgerStrokeStart: CGFloat = 0.0
    let hamburgerStrokeEnd: CGFloat = 0.0
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        

        //initBackGround()
        let path = CGPathCreateMutable()
         CGPathMoveToPoint(path, nil,0 ,  0 )
        CGPathAddArc(path, nil, 0, 0, 40, 0, CGFloat(M_PI * 2), false)
   
        self.middle.path = path

        for layer in [ self.middle ] {
            layer.fillColor = nil
            layer.strokeColor = UIColor(red: 255 / 255, green: 0 / 255, blue: 0 / 255, alpha: 0.8).CGColor
            layer.lineWidth = 10
            layer.miterLimit = 20
            layer.lineCap = kCALineJoinRound
            layer.masksToBounds = true
            
            layer.backgroundColor = UIColor(red: 0, green: 0, blue: 255, alpha: 0.1).CGColor

           // layer.backgroundColor = UIColor.grayColor().CGColor
            
            let strokingPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 6, CGLineCap.Round, CGLineJoin.Miter, 4)

            layer.bounds = CGPathGetPathBoundingBox(strokingPath)
//            layer.bounds = self.bounds
            
            print(layer.bounds,self.layer.bounds)

            layer.actions = [
                "strokeStart": NSNull(),
                "strokeEnd": NSNull(),
                "transform": NSNull()
            ]
            
            self.layer.addSublayer(layer)
            
        }

        
        self.middle.position = CGPoint(x: -middle.bounds.origin.x, y: -middle.bounds.origin.y)
        self.middle.strokeStart = hamburgerStrokeStart
        self.middle.strokeEnd = hamburgerStrokeEnd
        self.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
        
        
        //backView
        circlePointView = UIView(frame: CGRectMake(frame.width - 20, frame.height / 2 - 10, 20, 20))
        circlePointView.layer.cornerRadius = 10
        circlePointView.backgroundColor = UIColor(red: 255 / 255, green: 63 / 255, blue: 0 / 255, alpha: 1)
        self.addSubview(circlePointView)
    }

    let strokeEnd:CABasicAnimation = {
      
        let  ani = CABasicAnimation(keyPath: "strokeEnd")
        return ani
    }()

    var middle: CAShapeLayer! = CAShapeLayer()
    
    func initBackGround(){
        
        let path = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil,bounds.width / 2,  0 )
        CGPathAddArc(path, nil, 0, 0, bounds.width  / 2, 0, CGFloat(M_PI * 2), false)
    
        let backGroundLayer: CAShapeLayer! = CAShapeLayer()
        
        backGroundLayer.path = path
        backGroundLayer.fillColor = nil
        backGroundLayer.strokeColor = UIColor(red: 255 / 255, green: 202 / 255, blue: 190 / 255, alpha: 1).CGColor
        backGroundLayer.lineWidth = 2.0
        backGroundLayer.miterLimit = 20
        backGroundLayer.lineCap = kCALineJoinRound
        backGroundLayer.masksToBounds = true
        let strokingPath = CGPathCreateCopyByStrokingPath(path, nil, 6, CGLineCap.Round, CGLineJoin.Miter, 4)
        backGroundLayer.bounds = CGPathGetPathBoundingBox(strokingPath)
        backGroundLayer.position = CGPoint(x: -backGroundLayer.bounds.origin.x, y: -backGroundLayer.bounds.origin.y)
        backGroundLayer.strokeStart = CGFloat(0.0)
        backGroundLayer.strokeEnd = CGFloat(1.0)
        self.layer.addSublayer(backGroundLayer)
        
    }
    
    func run(end:CGFloat = 1.0){
    
        let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
        strokeEnd.fromValue = 0
        strokeEnd.toValue = end
        strokeEnd.duration = 2.0
        strokeEnd.timingFunction = CAMediaTimingFunction(controlPoints: 0.95, 0.5, 0.5, 1)
       // strokeEnd.repeatCount = 100
        self.middle.ocb_applyAnimation(strokeEnd)
    }
    
    func stop(result:Int){
        
        let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
        print("stop fromValue:\(strokeEnd.fromValue)")
        
        strokeEnd.fromValue = strokeEnd.toValue
        if result == 0{
            
            strokeEnd.toValue = 1
        }else{

            strokeEnd.toValue = 0
        }
        strokeEnd.duration = 0.2
        strokeEnd.timingFunction = CAMediaTimingFunction(controlPoints: 0, 0.0, 0.0, 0)
        strokeEnd.repeatCount = 1
        
        strokeEnd.beginTime = CACurrentMediaTime() + 0.1
        strokeEnd.fillMode = kCAFillModeBackwards
        
        self.middle.ocb_applyAnimation(strokeEnd)
        
    }
    
    func setButtonState(state:HamburgerButtonState){
    
        switch state{
        
        case .satrt:
            self.run()
        case let .stop(state):
            stop(state)
            
        }
    }
}

extension CALayer {
    func ocb_applyAnimation(animation: CABasicAnimation) {
        let copy = animation.copy() as! CABasicAnimation

        if copy.fromValue == nil {
            if let _:AnyObject = self.presentationLayer(){
            
                 copy.fromValue = self.presentationLayer()!.valueForKeyPath(copy.keyPath!)
            }
            
           
        }

        self.addAnimation(copy, forKey: copy.keyPath)
        self.setValue(copy.toValue, forKeyPath:copy.keyPath!)
    }
}
